<template>
  <div class="page-main"  v-title data-title="公司信息库">
    <home-nav :userData="userinfo"></home-nav>
    <div class="banner"><span>公司信息库</span></div>
    <div class="container">
      <div class="btn-line">
        <div>
          <a-button :loading="tabLoading" class="hte-btn" icon="reload" @click="doSearch">刷新</a-button>
          <a-button class="hte-btn add-btn" icon="import" type="primary" @click="addBatch" v-has="'company:addBatch'">批量入库</a-button>
          <a-button class="hte-btn add-btn" icon="import" type="primary" @click="importInitData" v-has="'company:addBatch'">初始化基本信息数据</a-button>
          <a-button class="hte-btn add-btn" icon="import" type="primary" @click="importAreaData" v-has="'company:addBatch'">初始化地址信息</a-button>
          <a-button class="hte-btn add-btn" icon="pushpin" type="primary" @click="pushMdm" v-has="'company:addBatch'">推送到MDM</a-button>
          <!-- <a-button class="hte-btn add-btn" icon="import" type="primary" @click="initHoldingParticipation" v-has="'company:addBatch'" :loading="holdLoading">初始化参股控股公司</a-button> -->
          <a-button class="hte-btn add-btn" icon="plus" @click="addNew" v-has="'company:edit'">新增</a-button>
          <a-button :loading="exportLoading" v-has="'company:edit'" icon="download"  @click="handleExportExcel">导出</a-button>
        </div>
        <a-input-search v-model="valueSearch" @search="doSearch" :allowClear="true" placeholder="请输入关键字进行搜索" />
      </div>
      <div class="cascade">
        <div class="projec-class-box clearFix" :class="{'project-class-more': more.moreRef0Class}" ref="moreRef0" >
          <div class="projec-class-lable">公司分类：</div>
          <ul class="projec-class-list clearFix" :class="{'projec-class-list-more': more.moreRef0}">
            <li
              v-for="item of projectTypes"
              :key="item.code"
              :class="['hoverShow', { active: projectStatus == item.code }]"
              @click="handleToggle(item.code, 'projectStatus')"
            >
              {{ item.name }}
            </li>            
          </ul>
          <div class="btn-more" @click="changeMore('moreRef0')">更多<a-icon :class="[ 'icon-child-down', { 'icon-child-up': more.moreRef0 }]" slot="suffixIcon" type="caret-up"/></div>
        </div>
        <div class="projec-class-box clearFix" :class="{'project-class-more': more.moreRef0Class}" ref="moreRef0" v-has="'company:edit'" >
          <div class="projec-class-lable">公司状态：</div>
          <ul class="projec-class-list clearFix" :class="{'projec-class-list-more': more.moreRef0}">
            <li
              v-for="item of companyStatusList"
              :key="item.code"
              :class="['hoverShow', { active: companyStatus == item.code }]"
              @click="handleToggle(item.code, 'companyStatus')"
            >
              {{ item.name }}
            </li>            
          </ul>
          <div class="btn-more" @click="changeMore('moreRef0')">更多<a-icon :class="[ 'icon-child-down', { 'icon-child-up': more.moreRef0 }]" slot="suffixIcon" type="caret-up"/></div>
        </div>  
      </div>
      <div class="content-list">
        <a-table
          class="hte-table-content"
          :columns="reservationColumns"
          :data-source="reservationData"
          :pagination="pagination"
          :loading="tabLoading"
          size="middle"
          @change="pageChange"
        >
          <template slot="name" slot-scope="text, record">            
            <a v-if="filterHasPermission('company:readDetail')" :title="text" @click="handleClick('det', record)">{{text}}</a>  
            <span :title="text" v-else>{{text}}</span>    
            <span v-if="checkIsStatus(record)" class="status">new</span>      
          </template>
          <template slot="operation" slot-scope="text, record">
            <!-- <a v-has="'company:readDetail'" class="mr10" title="查看详情" @click="handleClick('det', record)"
              ><span class="iconfont icon-wendang"></span
            ></a> -->
            <a title="编辑" v-has="'company:edit'" @click="handleClick('edit', record)"><span class="iconfont icon-shenqing"></span></a>
             <a-divider  v-has="'company:edit'" type="vertical" />
            <a title="变更历史" v-has="'company:edit'"  @click="handleClick('his', record)" type="history"><a-icon type="history" /></a>
             <a-divider  v-has="'company:edit'" type="vertical" />
            <a title="推送MDM" v-has="'company:edit'"  @click="mdmOk('single',record)"><a-icon type="pushpin" /></a>
          </template>
        </a-table>
        <ImportInitData ref="importInitData" @ok="doSearch"></ImportInitData>
         <importAreaData ref="importAreaData" @ok="doSearch"></importAreaData>
      </div>
    </div>
     <a-back-top  style="right:50px;"/>
      <a-modal :visible="mdmVisi" @ok="mdmOk('all')" title="推送公司信息到MDM" @cancel="mdmVisi=false" :confirmLoading="pushLoading">
            <template>
              <a-alert message="推送说明：" type="info" closable >
              <p slot="description">
              1、是：推送整个公司库信息到MDM（一般不使用）<br/>2、否：只推送未推送过或者推送失败的公司信息到MDM
              </p>
      </a-alert>
            </template>
            <a-form-model  class="hte-form-model" :labelCol="{ span: 6 }"
                  :wrapperCol="{ span: 18 }">
            <a-row :gutter="24" style="margin-bottom: 10px">
                <a-col :span="24">
                <a-form-model-item  label="是否全量推送">
                  <a-switch v-model="pushMdmAll" checked-children="是" un-checked-children="否" />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
      </a-modal>
  </div>
</template>
<script>
import { getAction,downloadFileLink } from '@/api/manage'
import { codeInfoList } from '@/api/codeInfo'
import {filterHasPermission} from '@/utils/hasPermission'
import { ResizeHandleMoreMixin } from '@/mixins/ResizeHandleMoreMixin'
import { getDaysBetween } from '@/utils/util'

export default {
  name: 'TaskHome',
  components: {
    HomeNav: () => import('@/components/layouts/HomeNav'),
    ImportInitData: () => import('@/views/library/company/components/ImportInitData'),
    ImportAreaData: () => import('@/views/library/company/components/ImportAreaData'),
  },
  mixins: [ResizeHandleMoreMixin],
  data() {
    return {
      userinfo: {
        info: this.$store.getters.userInfo,
        module: 'companyList',
      },
      reservationColumns: [
        { title: '公司名称', dataIndex: 'name', width: '27%', align: 'left',scopedSlots: { customRender: 'name' }, },
        { title: '统一社会信用代码', dataIndex: 'code', width: '18%', align: 'center',ellipsis: true, },
        { title: '法定代表人', dataIndex: 'legal', width: '12%', align: 'center',ellipsis: true, },
        { title: '成立日期', dataIndex: 'establishTime', align: 'center', width: '100px' },
        { title: '公司分类', dataIndex: 'companyClassName', width: '13%', align: 'center',ellipsis: true, },
        { title: '住所', dataIndex: 'addressAreaLabelCopy', width: '15%', align: 'center',ellipsis: true,},
        {
          title: '操作',
          dataIndex: 'operation',
          width: '100px',
          align: 'center',
          scopedSlots: { customRender: 'operation' },
        },        
      ],
      reservationData: [],
      pagination: {
        total: 0,
        current: 1,
        pageSize:10,
        showQuickJumper: true,
        showSizeChanger: true,
        pageSizeOptions: ['10', '30', '50'],
        showTotal: (total, range) => {
          return range[0] + '-' + range[1] + ' 共' + total + '条'
        },
      },
      tabLoading: false,
      currPageSize: 10,
      valueSearch: '',
      visibleModel: false,
      projectTypes: [],
      companyStatusList: [{ code: '', name: '全部'}, { code: '1', name: '创建中'},{ code: '2', name: '审批中'},{ code: '3', name: '已入库'},{ code: '10', name: '审批不通过'}],
      projectStatus: '',
      companyStatus: '3',
      exportLoading: false,
      holdLoading:false,
      mdmVisi:false,
      pushLoading:false,
      pushMdmAll:false,
    }
  },
  mounted() {
    this.getDics()
    this.getDataList()
  },
  methods: {
    filterHasPermission(value){
      return filterHasPermission(value)
    },
    getDics() {
      codeInfoList({ type: '公司库分类首页', column: 'code', order: 'Asc', pageNo: 0, pageSize: -1 }).then((res) => {
        if (res.code == 200 && res.result && res.result.records) {
          this.projectTypes = res.result.records || []
          this.projectTypes.splice(0, 0, { code: '', name: '全部', type: '公司库分类首页' })
          this.$nextTick(() => { 
            this.setBtnMore('moreRef0')
          });
        } else {
          this.$message.warning('字典加载失败:' + res.message)
        }
      })
    },
    addBatch(){
      let urlJump = this.$router.resolve({ path: '/company/batchCompany' })
      window.open(urlJump.href, '_blank')
    },
    importInitData(){
      this.$refs.importInitData.importExcelDataBtn()
    },
    importAreaData(){
        this.$refs.importAreaData.importExcelDataBtn()
    },
    initHoldingParticipation(){
      var vm = this
       this.$confirm({
          title: `是否确认初始化参股控股公司？`,
          onOk() {
          vm.holdLoading = true
            getAction('/libraryCompany/hteLibCompany/initHoldingParticipation', {
       
      }).then((res) => {
          if(res.code == 200){
            vm.$message.success('操作成功' )
              }else{
                vm.$message.warning('操作失败:' + res.message)
              }
            }).finally(res=>{
              vm.holdLoading = false
            })
          }
      })
       
    },
    addNew(){
      let urlJump = this.$router.resolve({ path: '/company/editor' })
      window.open(urlJump.href, '_blank')
    },
    doSearch(){
      this.pagination.current = 1
      this.getDataList()
    },
    /**
     * 查询
     */
    getDataList() {
      this.tabLoading = true
      getAction('/libraryCompany/hteLibCompany/pageList', {
        pageSize: this.currPageSize,
        pageNo: this.pagination.current,
        companyClass: this.projectStatus,
        companyStatus:this.companyStatus,
        keyword: this.valueSearch,
      }).then((res) => {
        if (res.code == 200 && res.result) {
          this.pagination.total = res.result.total
          const targe = '中国/'
          res.result.records.forEach((item, index) => {
            item.key = index
            if(item.addressAreaLabel && item.addressAreaLabel.indexOf(targe) === 0){
              item.addressAreaLabelCopy = item.addressAreaLabel.split(targe)[1] // 只显示省市区
            }
          })
          this.reservationData = res.result.records
          this.tabLoading = false
        } else {
          this.$message.warning('数据加载失败:' + res.message)
          this.tabLoading = false
        }
      })
    },
    pageChange(page) {
      this.currPageSize = page.pageSize
      this.pagination.pageSize = page.pageSize
      this.pagination.current = page.current
      this.getDataList()
    },    
    handleToggle(code, type){
      this[type] = code
      this.pagination.current = 1
      this.getDataList()
    },
    handleClick(type, item) {
      if (type === 'det') {
        let path = `/company/info?id=${item.id}`
        if(item.companyStatus < 3){
            path = `/company/editor?id=${item.id}` 
        }
        let urlJump = this.$router.resolve({ path: path })
        window.open(urlJump.href, '_blank')
      } else if(type === 'edit'){        
        let urlJump = this.$router.resolve({ path: `/company/editor?id=${item.id}` })
        window.open(urlJump.href, '_blank')
      }else if(type === 'his'){
        let urlJump = this.$router.resolve({ path: `/company/listHis?companyId=${item.id}` })
        window.open(urlJump.href, '_blank')
      }
    },
    /**
     * 对新入库createTime或发生信息变更lastTime的公司进行标志（时间维持1个月）
     */
    checkIsStatus(item){
      let cr = ''
      let la = ''      
      if(item.createTime){
        cr = getDaysBetween(item.createTime)
      }
      if(item.lastTime){
        la = getDaysBetween(item.lastTime)
      }
      return  (cr && cr <= 30) || (la && la <= 30)      
    },
    handleExportExcel(){
      let param = {companyStatus:this.companyStatus};
  
      console.log("导出参数",param)
      this.exportLoading = true;
      downloadFileLink('/libraryCompany/hteLibCompany/exportXls','公司库导出.xls', param,{type: 'application/vnd.ms-excel'}).then((data)=>{
        this.exportLoading = false;
      })
  
    },
    pushMdm(){
      this.pushMdmAll = false
      this.mdmVisi = true
      this.pushLoading = false
    },
    mdmOk(type,record){
       var vm = this

        let data = {forceUpdate:"1"} 
       if(type == 'all'){
         let forceUpdate = this.pushMdmAll?"1":"0"
         data.forceUpdate = forceUpdate
      } else{
        data.companyId = record.id
      }
       this.$confirm({
          title: `是否确认公司信息推送到MDM？`,
          onOk() {
            vm.pushLoading = true
             return new Promise((resolve, reject) => {
             getAction('/libraryCompany/hteLibCompany/pushCompanyToMdm',data).then(res=>{
                if(res.code == 200){
                  vm.$message.success('推送成功')
                  
                }else{
                  vm.$message.warning('推送失败:' + res.message)
                }
            }).finally(res=>{
                vm.mdmVisi = false
                vm.pushLoading = false
                resolve()
            })
          }).catch(() => console.log('Oops errors!'));
            
          }
      })
     
    },
  },
}
</script>
<style lang="less" scoped>
@import '~@assets/less/hte-main.less';
@import './index.less';
a.mr10 {
  margin-right: 10px;
  position: relative;
  padding-right: 10px;
  &:after {
    &:extend(.afterbg);
  }
}
.page-main .container .cascade{margin-bottom: 15px;}
.page-main .btn-line{
  margin-bottom: 10px;
  display: flex;
  justify-content: space-between;
  button{margin-right: 10px;margin-bottom: 8px;}
  .ant-input-search{width: 35%;height: 32px;}
}
.status{color: #fff;background-color: #ff5722;font-size: 12px;
    text-align: center;padding: 0px 2px;transform: scale(0.75);border-radius: 5px;display: inline-block;
    position: relative;top: -1px;height: 16px;line-height: 16px;margin-left: -2px;
}
</style>